package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Exam;
import cn.wolfcode.domain.Question;
import cn.wolfcode.mapper.ExamMapper;
import cn.wolfcode.mapper.QuestionMapper;
import cn.wolfcode.qo.ExamQueryObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class ExamServiceImpl implements IExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public void save(Exam exam, ExamQueryObject qo) {
        //把试卷id,试卷title,考试时长,总分给添加到exam表中
        examMapper.insert(exam);
        //去数据库找单选题,多选题,判读题的id
        List<Long> onlyIds = questionMapper.selectByTypeId(1);
        List<Long> manyIds = questionMapper.selectByTypeId(2);
        List<Long> trueOrFalseIds = questionMapper.selectByTypeId(3);
        //把获取出来的单选题,多选题,判读题的题号id的数组给打乱
        Collections.shuffle(onlyIds);
        Collections.shuffle(manyIds);
        Collections.shuffle(trueOrFalseIds);
        //根据用户输入的单选题,多选题,判读题的数量来随机生成单选题号的数组
        Integer onlyNum = qo.getOnlyNum();
        Integer manyNum = qo.getManyNum();
        Integer trueOrFalseNum = qo.getTrueOrFalseNum();
        //循环遍历题号数组,长度为用户输入的数量
        for (int i = 0; i < onlyNum; i++) {
            //往中间表给添加试卷id和单选题目id的关联关系
            questionMapper.insertByExamId(onlyIds.get(i), exam.getId(), qo.getOnlyScore());
        }
        for (int i = 0; i < manyNum; i++) {
            //往中间表给添加试卷id和多选题目id的关联关系
            questionMapper.insertByExamId(manyIds.get(i), exam.getId(), qo.getManyScore());
        }
        for (int i = 0; i < trueOrFalseNum; i++) {
            //往中间表给添加试卷id和判断题目id的关联关系
            questionMapper.insertByExamId(trueOrFalseIds.get(i), exam.getId(), qo.getTrueOrFalseScore());
        }


    }

    @Override
    public void delete(Long id) {
        examMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Exam exam) {
        examMapper.updateByPrimaryKey(exam);
    }

    @Override
    public Exam get(Long id) {
        Exam exam = examMapper.selectByPrimaryKey(id);
        return exam;
    }

    @Override
    public List<Exam> listAll() {
        return examMapper.selectAll();
    }

    @Override
    public PageInfo<Exam> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize()); //对下一句sql进行自动分页
        List<Exam> exams = examMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Exam>(exams);
    }
}
